package com.wx.plugin.mvc;

import com.wx.plugin.config.MPConfig;
import com.wx.plugin.constant.ValueConstant;
import com.wx.plugin.context.ThreadContext;
import com.wx.plugin.mp.core.WXAPI;
import com.wx.plugin.mp.core.WebAuthAPI;
import com.wx.plugin.mp.core.WebAuthUrlUtil;
import com.wx.plugin.mp.core.WebAuthVO;
import com.wx.plugin.repository.*;
import com.wx.plugin.service.AcctransService;
import com.wx.plugin.util.BusiUtil;
import com.wx.plugin.util.DateUtil;
import com.wx.plugin.util.JSONUtil;
import com.yangzcp.userpojo.*;
import io.github.elkan1788.mpsdk4j.vo.api.Follower;
import io.github.elkan1788.mpsdk4j.vo.api.QRTicket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class WebController {

    @Autowired
    private WXAPI wxapi;

    @Autowired
    private MembersRepository membersRepository;

    @Autowired
    private Sale_shenqiRepository sale_shenqiRepository;

    @Autowired
    private Members_accountRepository members_accountRepository;

    @Autowired
    private Members_account_logRepository members_account_logRepository;

    @Autowired
    private Members_account_log_onRepository members_account_log_onRepository;

    @Autowired
    private TransRepository transRepository;

    @Autowired
    private Members_yaoqingmaRepository members_yaoqingmaRepository;

    @Autowired
    private WebAuthAPI webAuthAPI;

    @Autowired
    private MPConfig mpConfig;

    @Autowired
    private TixianRepository tixianRepository;

    @Autowired
    private AcctransService acctransService;

    @RequestMapping(value = "/weixin/usercenter", method = RequestMethod.GET)
    public ModelAndView usercenter(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        if(members != null){
            result.getModel().put("members", members);
            result.getModel().put("refmembers", members.getRef_member());
            result.getModel().put("subscribe_time", DateUtil.format(new Date(members.getCreate_time()), "yyyy-MM-dd HH:mm:ss"));
            Members_account members_account = members_accountRepository.findByMemberId(members.getId());
            result.getModel().put("members_account", members_account);
            Integer sale_flag = members.getSale_flag();
            if(ValueConstant.YES.equals(sale_flag)){
                List<Members_account_log> members_account_logs = members_account_logRepository.findByMemberId(members.getId());
                result.getModel().put("members_account_logs", members_account_logs);
                int oneLevel = membersRepository.countOneLevelMembers(members.getId());
                int twoLevel = membersRepository.countTwoLevelMembers(members.getId());
                List<Members> memberses = membersRepository.ownerMembers(members.getId(), members.getId());
                result.getModel().put("oneLevel", oneLevel);
                result.getModel().put("twoLevel", twoLevel);
                result.getModel().put("ownerMembers", memberses);
//                Map<String, Object> oneLevelLogOn = members_account_log_onRepository.showLogOn(members.getId(), 1);
//                Map<String, Object> twoLevelLogOn = members_account_log_onRepository.showLogOn(members.getId(), 2);
//                result.getModel().put("oneLevelLogOn", oneLevelLogOn);
//                result.getModel().put("twoLevelLogOn", twoLevelLogOn);
                List<Members_account_log> fenrun = members_account_logRepository.findByMemberIdAndResonType(members.getId(), ValueConstant.FEN_RUN);
                result.getModel().put("fenrun", fenrun);
                List<Members_account_log> accountLogs = members_account_logRepository.findByMemberId(members.getId());
                result.getModel().put("accountLogs", accountLogs);
                if(ValueConstant.YES.equals(members.getSale_flag())){
                    if(members.getSale_level() == 1){
                        List<Trans> byOneTeamTrans = transRepository.findByOneTeamTrans(members.getId());
                        result.getModel().put("trans", byOneTeamTrans);
                    }else if(members.getSale_level() == 2){
                        List<Trans> byTwoTeamTrans = transRepository.findByTwoTeamTrans(members.getId());
                        result.getModel().put("trans", byTwoTeamTrans);
                    }
                }
                result.setViewName("weixin/fenxiao_usercenter");
            }else{
                List<Members_account_log> xiaofeilist = members_account_logRepository.findByMemberIdAndResonType(members.getId(), ValueConstant.TI_XIAN);
                result.getModel().put("xiaofeilist", xiaofeilist);
                List<Members_account_log> fenrunlist = members_account_logRepository.findByMemberIdAndResonType(members.getId(), ValueConstant.FEN_RUN);
                result.getModel().put("fenrunlist", fenrunlist);
                result.setViewName("weixin/usercenter");
            }
        }else{
            Follower follower = wxapi.getFollower(openid, "UTF-8");
            result.getModel().put("follower", follower);
            result.setViewName("weixin/unuser");
        }
        return result;
    }

    @RequestMapping(value = "/getopenid", method = RequestMethod.GET)
    public ModelAndView getopenid(@RequestParam("code") String code, @RequestParam(value = "state", required = false) String state,  HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        String authorization_code = webAuthAPI.getWebAccessToken(mpConfig.getAppid(), mpConfig.getSecret(), code, "authorization_code");
        WebAuthVO webAuthVO = JSONUtil.parse(authorization_code, WebAuthVO.class);
        request.getSession().setAttribute(ThreadContext.KEY_OPENID, webAuthVO.getOpenid());
        if(StringUtils.isEmpty(state)){
            request.setAttribute("message", "get openid: " + webAuthVO.getOpenid());
            result.setViewName("weixin/error_status");
            return result;
        }else{
            try {
                response.sendRedirect(URLDecoder.decode(state, "UTF-8"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return new ModelAndView();
        }
    }

    @RequestMapping(value = "/weixin/fenxiao_register", method = RequestMethod.GET)
    public ModelAndView fenxiao_register(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Sale_shenqi sale_shenqi = sale_shenqiRepository.findByWeixin_openid(openid);
        if(sale_shenqi != null && ValueConstant.YANGZ_AUDIT_FLASE.equals(sale_shenqi.getAudit_flag())){
            result.getModel().put("message", "团队申请成功，请等待审核");
            result.setViewName("weixin/success_status");
            return result;
        }
        Members members = membersRepository.findByWeixin_openid(openid);
        if(members != null && StringUtils.isEmpty(members.getTel())){
            result.getModel().put("message", "请先注册会员");
            result.setViewName("weixin/error_status");
            return result;
        }
        if(members != null && ValueConstant.YES.equals(members.getSale_flag())){
            try {
                response.sendRedirect("/weixin/usercenter");
                return new ModelAndView();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else if(members != null && ValueConstant.NO.equals(members.getSale_flag())){
            try {
                response.sendRedirect("/weixin/m_sale_register");
                return new ModelAndView();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else {
            String sign = UUID.randomUUID().toString();
            request.getSession().setAttribute(ThreadContext.KEY_SIGN, sign);
            result.getModel().put("sign", sign);
            result.setViewName("weixin/fenxiao_register");
            return result;
        }
    }

    @RequestMapping(value = "/weixin/shareurl", method = RequestMethod.GET)
    public ModelAndView shareurl(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        if(members != null && !StringUtils.isEmpty(members.getTel())){
            if(members.getLevel() == 1){
                try {
                    response.sendRedirect("/weixin/sharemp");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            try {
                response.sendRedirect("/weixin/sharepage/" + members.getYaoqing_ma());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            result.getModel().put("message", "尚未注册, 不能分享");
            result.setViewName("weixin/error_status");
        }
        return result;
    }

    @RequestMapping(value = "/weixin/share/{yaoqingma}", method = RequestMethod.GET)
    public ModelAndView share(@PathVariable(value = "yaoqingma",required = true) String yaoqingma, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        Members byYaoqing_ma = membersRepository.findByYaoqing_ma(yaoqingma);
        if(StringUtils.isEmpty(byYaoqing_ma.getTel())){
            result.getModel().put("message", "尚未注册, 不能分享");
            result.setViewName("weixin/error_status");
            return result;
        }
        result.getModel().put("members", byYaoqing_ma);
        QRTicket qrTicket = wxapi.createQR(yaoqingma, -1);
        String ticket = null;
        try {
            ticket = URLEncoder.encode(qrTicket.getTicket(), "UTF-8");
            result.getModel().put("url", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        result.setViewName("weixin/share");
        return result;
    }

    @RequestMapping(value = "/weixin/register", method = RequestMethod.GET)
    public ModelAndView register(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        if(checkLogin(request, response)){
            String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
            Members members = membersRepository.findByWeixin_openid(openid);
            if(members != null && !StringUtils.isEmpty(members.getTel())){
                try {
                    response.sendRedirect("/weixin/usercenter");
                    return new ModelAndView();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }else{
                Members_yaoqingma yaoqin = members_yaoqingmaRepository.findByOpenid(openid);
                if(yaoqin != null){
                    Members recommend = membersRepository.findByYaoqing_ma(yaoqin.getYaoqingma());
                    if(recommend.getRef_member() == null){
                        try {
                            response.sendRedirect("weixin/fenxiao_register.html");
                            return new ModelAndView();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }else{
                        String sign = UUID.randomUUID().toString();
                        request.getSession().setAttribute(ThreadContext.KEY_SIGN, sign);
                        request.setAttribute("sign", sign);
                        result.setViewName("weixin/register");
                    }
                }else{
                    String sign = UUID.randomUUID().toString();
                    request.getSession().setAttribute(ThreadContext.KEY_SIGN, sign);
                    request.setAttribute("sign", sign);
                    result.setViewName("weixin/register");
                }
                return result;
            }
        }else{
            return new ModelAndView();
        }
    }

    private boolean checkLogin(HttpServletRequest request, HttpServletResponse response){
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        if(openid == null){
            try {
                response.sendRedirect(WebAuthUrlUtil.getAuthUrl(mpConfig.getAppid(), mpConfig.getHost() + "/getopenid", request.getRequestURL().toString()));
                return false;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }

    @RequestMapping(value = "/register_do", method = RequestMethod.POST)
    public ModelAndView register_do(@RequestParam(value = "tel", required = true) String tel, @RequestParam(value = "nickname", required = true) String nickname, @RequestParam(value = "yzm", required = true) String yzm, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String sessionYzm = (String) request.getSession().getAttribute(ThreadContext.KEY_YZM);
        if(yzm.equals(sessionYzm)){
            String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
            Members dbmembers = membersRepository.findByWeixin_openid(openid);
            if(dbmembers != null){
                if(tel.equals(dbmembers.getTel())){
                    result.getModel().put("message", "该电话号码已注册");
                    result.setViewName("weixin/error_status");
                    return result;
                }
                dbmembers.setTel(tel);
                membersRepository.save(dbmembers);
            }else{
                Follower follower = wxapi.getFollower(openid, "UTF-8");
                Members_yaoqingma yaoqin = members_yaoqingmaRepository.findByOpenid(follower.getOpenid());
                Members members = new Members();
                members.setTel(tel);
                members.setName(nickname);
                members.setWeixin_openid(follower.getOpenid());
                members.setCity(follower.getCity());
                members.setCountry(follower.getCountry());
                members.setProvince(follower.getProvince());
                members.setPhoto(follower.getHeadimgurl());
                members.setSex(BusiUtil.getSex(follower.getSex()));
                members.setYaoqing_ma(follower.getOpenid());
                members.setSubscribe_time(follower.getSubscribeTime());
                if(yaoqin == null){
                    members.setLevel(1);
                    members.setRef_member(null);
                    members.setRecommend_id2(null);
                    members.setSale_flag(ValueConstant.NO);
                }else{
                    Members recommend = membersRepository.findByYaoqing_ma(yaoqin.getYaoqingma());
                    members.setLevel(recommend.getLevel() + 1);
                    members.setRef_member(recommend);
                    if(recommend.getRef_member() != null){
                        members.setRecommend_id2(recommend.getRef_member().getId());
                    }
                    if(ValueConstant.YES.equals(recommend.getSale_flag())){
                        members.setSale_id(recommend.getId());
                    }else{
                        members.setSale_id(recommend.getSale_id());
                    }
                    members.setSale_flag(ValueConstant.NO);
                }
                membersRepository.save(members);
                Members_account members_account = new Members_account();
                members_account.setRef_member(members);
                members_account.setMoney(new BigDecimal(0));
                members_account.setGain_money(new BigDecimal(0));
                members_account.setSale_flag(ValueConstant.NO);
                members_account.setUpdate_time(new Date().getTime());
                members_account.setVersion(1);
                members_accountRepository.save(members_account);
            }
            result.getModel().put("message", "注册成功");
            result.setViewName("weixin/success_status");
        }else{
            result.getModel().put("message", "注册失败, 验证码错误");
            result.setViewName("weixin/error_status");
        }
        return result;
    }

    @RequestMapping(value = "/sale_register_do", method = RequestMethod.POST)
    public ModelAndView sale_register_do(@RequestParam(value = "tel", required = true) String tel, @RequestParam(value = "nickname", required = true) String nickname, @RequestParam(value = "yzm", required = true) String yzm, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String sessionYzm = (String) request.getSession().getAttribute(ThreadContext.KEY_YZM);
        if(yzm.equals(sessionYzm)){
            String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
            Sale_shenqi byWeixin_openid = sale_shenqiRepository.findByWeixin_openid(openid);
            if(byWeixin_openid != null){
                if(ValueConstant.YANGZ_AUDIT_TRUE.equals(byWeixin_openid.getAudit_flag())){
                    result.getModel().put("message", "团队申请已通过审核, 无需申请");
                    result.setViewName("weixin/error_status");
                    return result;
                }else{
                    sale_shenqiRepository.delete(byWeixin_openid);
                }
            }
            Follower follower = wxapi.getFollower(openid, "UTF-8");
            Sale_shenqi saleshenqi = new Sale_shenqi();
            saleshenqi.setTel(tel);
            saleshenqi.setName(nickname);
            saleshenqi.setWeixin_openid(follower.getOpenid());
            saleshenqi.setRef_member(null);
            saleshenqi.setAudit_flag(ValueConstant.YANGZ_AUDIT_FLASE);
            sale_shenqiRepository.save(saleshenqi);
            result.getModel().put("message", "团队申请成功，请等待审核");
            result.setViewName("weixin/success_status_nobutton");
        }else{
            result.getModel().put("message", "团队申请失败");
            result.setViewName("weixin/error_status");
        }
        return result;
    }

    @RequestMapping(value = "/weixin/m_sale_register", method = RequestMethod.GET)
    public ModelAndView m_sale_register(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        result.getModel().put("subscribe_time", DateUtil.format(new Date(members.getCreate_time()), "yyyy-MM-dd HH:mm:ss"));
        Members_account members_account = members_accountRepository.findByMemberId(members.getId());
        result.getModel().put("members_account", members_account);
        result.getModel().put("members", members);
        result.setViewName("weixin/member_fenxiao_register");
        return result;
    }
    @RequestMapping(value = "/m_sale_register_do", method = RequestMethod.GET)
    public ModelAndView m_sale_register_do(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        Sale_shenqi byWeixin_openid = sale_shenqiRepository.findByWeixin_openid(openid);
        if(byWeixin_openid == null){
            Sale_shenqi saleshenqi = new Sale_shenqi();
            saleshenqi.setTel(members.getTel());
            saleshenqi.setName(members.getName());
            saleshenqi.setWeixin_openid(openid);
            saleshenqi.setRef_member(null);
            saleshenqi.setAudit_flag(ValueConstant.YANGZ_AUDIT_FLASE);
            sale_shenqiRepository.save(saleshenqi);
        }
        result.getModel().put("message", "团队申请成功，请等待审核");
        result.setViewName("weixin/success_status");
        return result;
    }

    @RequestMapping(value = "/weixin/edit_profile", method = RequestMethod.GET)
    public ModelAndView edit_profile(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        Members_account memberAccount = members_accountRepository.findByMemberId(members.getId());
        result.getModel().put("members", members);
        result.getModel().put("members_account", memberAccount);
        return result;
    }

    @RequestMapping(value = "/edit_profile_do", method = RequestMethod.POST)
    public ModelAndView edit_profile_do(@RequestParam("bank") String bank, @RequestParam("card") String card, @RequestParam("cardname") String cardname,HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        members.setTixian_bank(bank);
        members.setTixian_card(card);
        members.setTixian_name(cardname);
        membersRepository.save(members);
        result.getModel().put("message", "修改成功");
        result.setViewName("weixin/success_status");
        return result;
    }

    @RequestMapping(value = "/weixin/tixian", method = RequestMethod.GET)
     public ModelAndView tixian(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        Members_account byMemberId = members_accountRepository.findByMemberId(members.getId());
        result.getModel().put("members", members);
        result.getModel().put("members_account", byMemberId);
        result.setViewName("weixin/tixian");
        return result;
    }

    @RequestMapping(value = "/tixian_apply_do", method = RequestMethod.POST)
    public ModelAndView tixian_apply_do(@RequestParam("amount") BigDecimal amount, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(amount);
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        Members_account byMemberId = members_accountRepository.findByMemberId(members.getId());
        Tixian_apply existsTixian = tixianRepository.existsTixian(members.getId(), ValueConstant.TIXIAN_DAI);
        if(existsTixian == null){
            if(StringUtils.isEmpty(members.getTixian_card())){
                result.getModel().put("message", "请先设置银行卡号");
                result.setViewName("weixin/error_status");
            }else if(amount.doubleValue() > byMemberId.getMoney().doubleValue()){
                result.getModel().put("message", "提现金额大于账户余额");
                result.setViewName("weixin/error_status");
            }else{
                Tixian_apply tixian_apply = new Tixian_apply();
                tixian_apply.setRef_member(members);
                tixian_apply.setTixian_flag(ValueConstant.TIXIAN_DAI);
                tixian_apply.setAmount(amount);
                tixian_apply.setTixian_bank(members.getTixian_bank());
                tixian_apply.setTixian_card(members.getTixian_card());
                tixian_apply.setTixian_name(members.getTixian_name());
                try {
                    tixianRepository.save(tixian_apply);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                acctransService.jianAccount(members, amount, "提现申请", ValueConstant.TI_XIAN, "提现申请");
                result.getModel().put("message", "提现申请成功，请等待审核");
                result.setViewName("weixin/success_status");
            }
        }else{
            result.getModel().put("message", "已经有一笔提现，请等待审核");
            result.setViewName("weixin/success_status");
        }
        return result;
    }

    @RequestMapping(value = "/weixin/jifen/tixian", method = RequestMethod.GET)
    public ModelAndView jifen_tixian(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        if(members != null){
            Members_account byMemberId = members_accountRepository.findByMemberId(members.getId());
            result.getModel().put("members", members);
            result.getModel().put("members_account", byMemberId);
            result.setViewName("weixin/point_duihuan");
        }else{
            result.getModel().put("message", "请先注册会员");
            result.setViewName("weixin/error_status");
        }
        return result;
    }

    @RequestMapping(value = "/jifen_tixian_apply_do", method = RequestMethod.POST)
    public ModelAndView jifen_tixian_apply(@RequestParam("amount") BigDecimal amount, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        checkLogin(request, response);
        String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
        Members members = membersRepository.findByWeixin_openid(openid);
        Members_account byMemberId = members_accountRepository.findByMemberId(members.getId());
        Tixian_apply existsTixian = tixianRepository.existsTixian(members.getId(), ValueConstant.TIXIAN_DAI);
        if(existsTixian == null){
            if(StringUtils.isEmpty(members.getTixian_card())){
                result.getModel().put("message", "请先设置银行卡号");
                result.setViewName("weixin/error_status");
            }else if(amount.doubleValue() > byMemberId.getMoney().doubleValue()){
                result.getModel().put("message", "兑换积分大于账户积分");
                result.setViewName("weixin/error_status");
            }else{
                Tixian_apply tixian_apply = new Tixian_apply();
                tixian_apply.setRef_member(members);
                tixian_apply.setTixian_flag(ValueConstant.TIXIAN_DAI);
                tixian_apply.setAmount(amount);
                tixian_apply.setTixian_bank(members.getTixian_bank());
                tixian_apply.setTixian_card(members.getTixian_card());
                tixian_apply.setTixian_name(members.getTixian_name());
                try {
                    tixianRepository.save(tixian_apply);
                } catch (Exception e) {
                }
                acctransService.jianAccount(members, amount, "积分兑换", ValueConstant.TI_XIAN, "积分兑换");
                result.getModel().put("message", "兑换申请成功，请等待审核");
                result.setViewName("weixin/success_status");
            }
        }else{
            result.getModel().put("message", "已经有一笔兑换或提现申请，请等待审核");
            result.setViewName("weixin/success_status");
        }
        return result;
    }

    @RequestMapping(value = "/weixin/sharepage/{yaoqingma}", method = RequestMethod.GET)
    public ModelAndView sharepage(@PathVariable(value = "yaoqingma", required = true) String yaoqingma, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        Members byYaoqing_ma = membersRepository.findByYaoqing_ma(yaoqingma);
        if(StringUtils.isEmpty(byYaoqing_ma.getTel())){
            result.getModel().put("message", "尚未注册, 不能分享");
            result.setViewName("weixin/error_status");
            return result;
        }
        result.getModel().put("members", byYaoqing_ma);
        result.getModel().put("yaoqingma", yaoqingma);
        result.setViewName("weixin/sharepage");
        return result;
    }

    @RequestMapping(value = "/weixin/sharemp", method = RequestMethod.GET)
    public ModelAndView sharepage(HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        result.setViewName("weixin/sharemp");
        return result;
    }

    @RequestMapping(value = "/weixin/sharepageregister/{yaoqingma}", method = RequestMethod.GET)
    public ModelAndView sharepageregister(@PathVariable(value = "yaoqingma",required = true) String yaoqingma, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        if(checkLogin(request, response)){
            String openid = (String) request.getSession().getAttribute(ThreadContext.KEY_OPENID);
            Members_yaoqingma members_yaoqingma = new Members_yaoqingma();
            members_yaoqingma.setOpenid(openid);
            members_yaoqingma.setYaoqingma(yaoqingma);
            Members_yaoqingma byOpenid = members_yaoqingmaRepository.findByOpenid(openid);
            if(byOpenid == null){
                members_yaoqingmaRepository.save(members_yaoqingma);
            }else{
                byOpenid.setYaoqingma(yaoqingma);
                members_yaoqingmaRepository.save(byOpenid);
            }
        }
        try {
            response.sendRedirect("/weixin/register");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


}
